// 发布订阅+观察者
class Channel {
      //中间第三方平台
      constructor() {
        this.topics = {}
      }
      addTopic(topicName) {
        this.topics[topicName] = [];
      }
      removeTopic(topicName) {
        delete this.topics[topicName]
      }
      subTopic(topicName, sub) {
        if (this.topics[topicName]) {
          this.topics[topicName].push(sub)
        }
      }
      unSubTopic(topicName, sub) {
        if (this.topics[topicName]) {
          let index = this.topics[topicName].indexOf(sub)
          this.topics[topicName].splice(index, 1)
        }
      }
      publish(topicName) {
        if (this.topics[topicName]) {
          this.topics[topicName].forEach((item) => {
            item.update(topicName);
          })
        }
      }
    }
    
    // 发布者dep
    class Publisher {
      constructor(name, channel) {
        this.name = name;
        this.channel = channel;
      }
      //注册报纸
      addTopic(topicName) {
        this.channel.addTopic(topicName);
      }
      //删除报纸
      removeTopic(topicName) {
        this.channel.removeTopic(topicName);
      }
      //发布
      publish(topicName) {
        this.channel.publish(topicName);
      }
    
    }
    
    // 订阅者watcher
    class Subscriber {
      constructor(name, channel) {
        this.name = name;
        this.channel = channel;
      }
      //订阅报纸
      subTopic(topicName) {
        this.channel.subTopic(topicName, this);
      }
      //取消订阅报纸
      unSubTopic(topicName) {
        this.channel.unSubTopic(topicName, this);
      }
      //通知该报纸所有订阅者更新
      update(topicName) {
        console.log(`我是${this.name},${topicName}更新了快去看`);
      }
    }
    
    
    let chan = new Channel()
    
    
    let p = new Publisher('1号报社', chan)
    let p2 = new Publisher('2号报社', chan)
    
    let sub = new Subscriber('zw', chan)
    let lx = new Subscriber('lx', chan)
    
    p.addTopic('红宝书')
    p2.addTopic('宝书')
    sub.subTopic('红宝书')
    sub.subTopic('宝书')
    lx.subTopic('红宝书')
    console.log(chan.topics, '测试红宝书注册和订阅')
    
    p.addTopic('绿宝书')
    sub.subTopic('绿宝书')
    sub.unSubTopic('绿宝书')
    console.log(chan.topics, '测试绿宝书删除订阅')
    p.removeTopic('绿宝书')
    console.log(chan.topics, '测试绿宝书删除注册')
    
    
    setTimeout(() => {
      p.publish('红宝书')
      p2.publish('宝书')
    }, 2000)